有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我在函数中有一个空指针异常,不知道如何修复它

功能是:

public Integer[] details;
private void putDetails(Integer l){
    if (l != null){
        int n = new Integer(0);
        n = details[l];
        details[l]=n+1;
    }
}

错误消息显示:

java.lang.NullPointerException
    at operacional.an_lex.putDetails(an_lex.java:30)

其中第30行是:n = details[l];

你能帮我吗


共 (1) 个答案

  1. # 1 楼答案

    您需要初始化details数组:

    //some number is the size of the array
    int[] details = new int[some number]; 
    

    或者,如果要用0填充元素,也可以这样初始化:

    int[] details = new int[]{0,0,0,0}; 
    

    发生的情况是,您正在从details数组中获取一个元素,但该元素没有值。我会检查以确保在该数组的元素中有赋值